package com.etheart.lyric.htmlparser.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.etheart.framework.core.util.RegexUtils;


public class LyricParseUtils {
	private static final Log logger = LogFactory.getLog(LyricParseUtils.class);
	
	public static List<LyricLine> parseLyric(File file){
		List<LyricLine> lines = new ArrayList<LyricLine>();
		if (!file.exists()) {
			return lines;
		}
		String line ="";
		BufferedReader reader;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
			while((line =reader.readLine())!=null){
				List<String> times = parseLineTime(line);
				for (String t : times) {
					LyricLine ll = new LyricLine(t, removeAllTime(line));
					lines.add(ll);
				}
			}
		} catch (FileNotFoundException e) {
			logger.error("文件不存在："+file.getAbsolutePath(),e);
		} catch (IOException e) {
			logger.error("文件读取错误："+file.getAbsolutePath(),e);
		}
		Collections.sort(lines);
		return lines;
	}
	
	public static String getLyricContent(File file){
		List<LyricLine> lines = parseLyric(file);
		StringBuffer buffer = new StringBuffer();
		for (LyricLine ll : lines) {
			buffer.append(ll.getLine()+"\r\n");
		}
		return buffer.toString();
	}
	
	private static List<String>  parseLineTime(String line){
		String reg = "\\[(\\d{2}:\\d{2}\\.\\d{2})\\]";
		List<String> times = RegexUtils.getMatcheGroups(reg, line);
		return times;
	}
	private static String removeAllTime(String line){
		String reg = "\\[(\\d{2}:\\d{2}\\.\\d{2})\\]";
		return line.replaceAll(reg, "");
	}
}
